package cn.com.io.day20151215;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * 若担心Channel对应的文件过大，使用map方法一次将所有文件内容映射到内在中引起性能下降，也可以使用Channel和Buffer传统的“用笔筒多次重复取消”的方式
 */
public class ReadFile {
    public static void main(String[] args) throws IOException {
        FileChannel channel = null;
        try {
            File file = new File("./src/cn/com/io/day20151215/ReadFile.java");
            channel = new FileInputStream(file).getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int i = 0;
            while(channel.read(buffer) != -1){
                buffer.flip();
                Charset charset = Charset.forName("UTF-8");
                CharBuffer charBuffer = charset.newDecoder().decode(buffer);
                System.out.println(charBuffer);
                buffer.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (channel !=null ){
                channel.close();
            }
        }
    }
}
